package com.shangke.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChatClient {
	public void chat(String host,int port){
		Socket socket=null;
		InputStream inputStream=null;
		OutputStream outputStream=null;
		Scanner scanner=null;
		try {
			//1.打开socked连接，连接服务器
			socket=new Socket(host,port);
			System.out.println("连接服务器成功！");
			//2.打开输入输出流
			inputStream=socket.getInputStream();
			outputStream=socket.getOutputStream();
			scanner=new Scanner(System.in);
			byte[] buffer=new byte[512];
			
			while(true){
				//3.打开键盘输入，并输入聊天内容
				System.out.print("请输入聊天内容：");
				String words=scanner.nextLine();
				//把聊天内容发生到服务器
				outputStream.write(words.getBytes());
				System.out.println("发送到服务器成功！");
				
				int len=inputStream.read(buffer);
				String reply=new String(buffer, 0, len).trim();
				System.out.println(reply);
				//如果用户输入quit,
				if ("quit".equalsIgnoreCase(reply)) {
					break;
				}
			}	
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			closeAll(scanner, inputStream, outputStream, socket);
		}
	}
	private void closeAll(Scanner scanner,InputStream inputStream,OutputStream outputStream,Socket socket){
		if (scanner != null) {
			scanner.close();
		}
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
			}
		}
		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
			}
		}
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}
	}
	public static void main(String[] args) {
		String host="192.168.1.29";
		int port=8888;
		ChatClient chatClient=new ChatClient();
		chatClient.chat(host, port);
	}

}
